﻿#include <QApplication>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QWindow>
#include <QQmlContext>
#include <QQmlEngine>
#include <QUrl>

#include "helper/log.h"
#include "helper/settingshelper.h"
#include "helper/network.h"
#include "helper/appinfo.h"
#include "helper/projectdbhelper.h"
#include "helper/projectfilewatcher.h"
#include "helper/translatehelper.h"
#include "component/filui.h"
#include "component/FpsItem.h"
#include "version.h"
#include "filapp.h"

#ifdef WIN32
#  include "common/app_dmp.h"
#endif

FilApp::FilApp(QObject *parent)
    : QObject{parent}
{}

FilApp::~FilApp()
{

}

int filmain(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QStringList arguments = app.arguments();
    const char *uri = "SecAssistPro";
    int major = 1;
    int minor = 0;

    qputenv("QML_XHR_ALLOW_FILE_READ", "1");

#ifdef WIN32
    ::SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)MyUnhandledExceptionFilter);
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
    qputenv("QT_QUICK_CONTROLS_STYLE", "Basic");
#else
    qputenv("QT_QUICK_CONTROLS_STYLE", "Default");
#endif
#ifdef Q_OS_LINUX
    // fix bug UOSv20 does not print logs
    qputenv("QT_LOGGING_RULES", "");
    // fix bug UOSv20 v-sync does not work
    qputenv("QSG_RENDER_LOOP", "basic");
#endif

    QApplication::setOrganizationName("TimeChicken");
    QApplication::setOrganizationDomain("https://timechicken.cc");
    QApplication::setApplicationName("SecAssistPro");
    QApplication::setApplicationDisplayName("SecAssistPro");
    QApplication::setApplicationVersion(APPLICATION_VERSION);
    // QApplication::setQuitOnLastWindowClosed(false);


    Log::setup(argv, uri);
    SettingsHelper::getInstance()->init(argv);

#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
    QQuickWindow::setGraphicsApi(QSGRendererInterface::OpenGL);
#endif
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
    QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#  if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
    QApplication::setHighDpiScaleFactorRoundingPolicy(
        Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
#  endif
#endif

    QQmlApplicationEngine engine;
    TranslateHelper::getInstance()->init(&engine);
    engine.rootContext()->setContextProperty("SettingsHelper", SettingsHelper::getInstance());
    engine.rootContext()->setContextProperty("ProjectDbHelper", ProjectDbHelper::getInstance());
    engine.rootContext()->setContextProperty("ProjectFileWatcher", ProjectFileWatcher::getInstance());
    engine.rootContext()->setContextProperty("TranslateHelper", TranslateHelper::getInstance());
    engine.rootContext()->setContextProperty("Network", Network::getInstance());
    engine.rootContext()->setContextProperty("AppInfo", AppInfo::getInstance());
    //@uri SecAssistPro
    qmlRegisterType<ProjectDbHelperCallable>(uri, major, minor, "ProjectDbHelperCallable");
    qmlRegisterUncreatableMetaObject            (ProjectDbHelperColumnIndexType::staticMetaObject, uri, major, minor,
                                                "ProjectDbHelperColumnIndexType", "Access to enums & flags only");
    FilUI::registerTypes(&engine);


    QUrl url(QStringLiteral("qrc:/qml/window/MainWindow.qml"));
    if (arguments.size() >= 2 && arguments.at(1).startsWith("-crashed=")) {
        url.setUrl(QStringLiteral("qrc:/qml/window/CrashWindow.qml"));
    }
    QObject::connect(
        &engine,
        &QQmlApplicationEngine::objectCreated,
        &app,
        [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        },
        Qt::QueuedConnection);
    engine.load(url);

    // return app.exec();
    const int exec = QApplication::exec();
    if (exec == 931) {
        QProcess::startDetached(qApp->applicationFilePath(), qApp->arguments());
    }
    return exec;
}
